package com.bridgetree.jubaocrm.ui;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Transaction;

public class TransactionDetailsActivity extends Activity {
	private Context mContext;
	private final String tag = "TransactionDetailsActivity";
	private Transaction mTransaction;
	private boolean isDone=false;
	private TextView data_tv;
	private TextView txt;
	private Button delete;
	public static String timeString ="";
	public static String txtString ="";
	private String user_id = "";
	private String token = "";
	private SharedPreferences prefs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transaction);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(tag, "intent is null");
			return;
		}
		isDone=false;
		prefs = PreferenceManager
		.getDefaultSharedPreferences(TransactionDetailsActivity.this);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		TextView xm_sp_tv_title = (TextView) findViewById(R.id.xm_sp_tv_title);
		data_tv = (TextView) findViewById(R.id.data_tv);
		txt = (TextView) findViewById(R.id.txt);
		delete = (Button) findViewById(R.id.delete);

		if (intent.getExtras() != null) {
			mTransaction = (Transaction)intent.getExtras().getSerializable("Transaction");
			timeString = mTransaction.getReminder_time();
			txtString = mTransaction.getContent();
			data_tv.setText(timeString);
			txt.setText(txtString);
		}
		xm_sp_tv_title.setText("事务明细");

		findViewById(R.id.xm_sp_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (isDone) {
							Intent intent = new Intent();
							setResult(0x0005, intent);
						}
						finish();
					}
				});

		findViewById(R.id.xm_sp_RelativeLayout_edit).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						//编辑
						if(mTransaction!=null){
							isDone=true;
							Intent intent = new Intent(mContext,TransactionEditActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString("rid", mTransaction.getReminder_id());
							intent.putExtras(bundle);
							startActivityForResult(intent, 100001);
						}
					}
				});

		delete.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						//删除
						if(mTransaction!=null){
							getDelete();
						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 100001){
			if(resultCode==0x001){
				data_tv.setText(timeString);
				txt.setText(txtString);
			}
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				setResult(0x0005, intent);
				finish();
			}
		}).show();
	}

	private void getDelete() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else{
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			//rid=1
			//&user_id=cd34350bb2844077bfbd4abe5ec56f99
			//&token=b0a4c4f0cdcc4f668d0baf913fa8e463
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("rid", mTransaction.getReminder_id());
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/reminder/del";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("删除事务  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
										openDailog("网络提示", "删除事务成功！");
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														openDailog("失败提示", desc);
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

}
